package v2ray

import (
	"context"
	"errors"
	"gitee.com/Luna-CY/hui-hui/internal/application/app"
	"gitee.com/Luna-CY/hui-hui/internal/interface/application"
	"gitee.com/Luna-CY/hui-hui/internal/logger"
	"gitee.com/Luna-CY/hui-hui/internal/toolbox/processor"
	"gitee.com/Luna-CY/hui-hui/internal/util/point"
	"path/filepath"
)

func (cls *V2ray) Start(ctx context.Context, restart bool) error {
	if err := cls.ApplyConfig(ctx); nil != err {
		return err
	}

	var state, _, _, _, _ = cls.GetState()
	if application.Running == state || application.Reloading == state {
		return nil
	}

	var config = cls.GetConfig()
	if 0 == len(config.Inbounds) || 0 == len(config.Outbounds) {
		return errors.New("启动失败，V2ray配置无效，V2ray需要最少一条入站和出站协议，请前往配置管理更新配置后启动应用")
	}

	logger.GetLogger().Sugar().Infof("启动V2ray服务: %s -c %s", filepath.Join(rootPath, "v2ray"), configFilePath)

	if err := cls.processor.StartApplication("V2ray", filepath.Join(rootPath, "v2ray"), []string{"run", "-c", configFilePath}, nil, rootPath, restart, func(state processor.State, err error) {
		cls.UpdateState(app.ProcessStateMapping[state], 0, point.ErrorMessage(err))
	}); nil != err {
		cls.UpdateState(application.RunError, 0, err.Error())
	}

	return nil
}
